package chapter8.eg1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

public class BootstrapExample {

  @Test
  public void testBootstrap() throws InterruptedException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup())
        .channel(NioSocketChannel.class)
        .handler(new SimpleChannelInboundHandler<ByteBuf>() {
          @Override
          protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            System.out.println("Received Data from server: " + msg.toString(CharsetUtil.UTF_8));
          }

          @Override
          public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // 注意这里要使用ByteBuf封装要发送的数据
            ctx.writeAndFlush(Unpooled.copiedBuffer("Send data to server".getBytes()));
          }
        });

    ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)).sync();
    future.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
          System.out.println("Connection established");
        } else {
          System.err.println("Connection attempt failed");
          future.cause().printStackTrace();
        }
      }
    });



    TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
  }

}
